//
//  DiscoverHouseholdListViewController.m
//  HJB
//
//  Created by jiezsoft.com on 14-10-10.
//  Copyright (c) 2014年 jiezsoft.com. All rights reserved.
//

#import "DiscoverHouseholdListViewController.h"
#import "HouseholdDetailViewController.h"
#import "UIViewExt.h"
#import "CycleScrollViews.h"
#import "HttpRequest.h"
#import "UIButton+WebCache.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "HouseholdListCell.h"
#import "TheLoginViewController.h"
#import "ToBindCompanyViewController.h"
#import "LoginCompanysViewController.h"
@interface DiscoverHouseholdListViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (strong, nonatomic) NSString *ImageUrlStr;
@property (strong, nonatomic) NSString*contentStr;
@property (strong, nonatomic) NSString*titleStr;

@end
@implementation DiscoverHouseholdListViewController

{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*fid;
    NSMutableArray*title;
    NSMutableArray*content;
    NSMutableArray*imageUrl;
    NSMutableArray*author;
    NSMutableArray*pubTime;
    NSMutableArray*collectCount;
    NSMutableArray*commentCount;
    NSMutableArray*LinkType;
    NSMutableArray*LinkCode;
    NSMutableArray*ImageUrl;
    int pageNumber;
    CycleScrollViews *mainScorllView;
    NSString *result;
    float lastContentOffset;
    NSString*TotalCount;
    UITableView *table;
    UIView*noDataView;
    UIButton *userStatusBtn;
}
@synthesize alt = alt;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"发现";
        
    }
    return self;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.title = @"资讯";
    [[self rdv_tabBarController] setTabBarHidden:self.isHidden];
    self.navigationController.navigationBarHidden=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    self.navigationController.delegate = self;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction) forControlEvents:UIControlEventTouchUpInside];
    backButton.hidden=!self.isHidden;
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //   [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ChangeToken) name:@"s" object:Nil];    [table removeFromSuperview];
    
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self ChangeToken];
    [userStatusBtn removeFromSuperview];
     [noDataView removeFromSuperview];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]) {
        userStatusBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2-60,ScreenHeight/2-50, 120, 25)];
        [userStatusBtn setTitle:@"认证中...请等待！" forState:UIControlStateNormal];
        userStatusBtn.backgroundColor=luseColor;
        [userStatusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        userStatusBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [userStatusBtn addTarget:self action:@selector(userStatus) forControlEvents:UIControlEventTouchUpInside];
        userStatusBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [self.view addSubview:userStatusBtn];

    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        userStatusBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2-60,ScreenHeight/2-50, 120, 25)];
        [userStatusBtn setTitle:@"去认证门店先！" forState:UIControlStateNormal];
        userStatusBtn.backgroundColor=luseColor;
        [userStatusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        userStatusBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        userStatusBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [userStatusBtn addTarget:self action:@selector(userStatus) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:userStatusBtn];
    }

  }



-(void)userStatus{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
        Login.viewSat=@"The original road";
        [self.navigationController pushViewController:Login animated:YES];
    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]) {
        
        LoginCompanysViewController * Login=[[LoginCompanysViewController alloc]init];
        [self.navigationController pushViewController:Login animated:YES];
        }

}


-(void)BackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)ChangeToken
{

    [self requestData];

}


- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self userStatus];
    
}
-(void)requestData{
    self.sat=nil;
    pageNumber=1;
    [table removeFromSuperview];
    [noDataView removeFromSuperview];
    
    pubTime= [[NSMutableArray alloc] init];
    author= [[NSMutableArray alloc] init];
    ImageUrl= [[NSMutableArray alloc] init];
    content= [[NSMutableArray alloc] init];
    title= [[NSMutableArray alloc] init];
    fid= [[NSMutableArray alloc] init];
    LinkType= [[NSMutableArray alloc] init];
    LinkCode= [[NSMutableArray alloc] init];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    UIView*foot=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    foot.backgroundColor=[UIColor whiteColor];
    table.tableFooterView=foot;
    
    [self addFooter];
    [self addheader];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"30" forKey:@"pageSize"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"/Discover/Household/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    
                    [author addObject:[dicc valueForKey:@"author"]];
                    [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                    [content addObject:[dicc valueForKey:@"content"]];
                    [fid addObject:[dicc valueForKey:@"fid"]];
                    [title addObject:[dicc valueForKey:@"title"]];
                    
                    NSString* string =  [dicc valueForKey:@"pubTime"];
                    //                    NSLog(@"-------------%@",string);
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                    NSDate *destDate= [dateFormatter dateFromString:string];
                    
                    NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                    timeInterval = -timeInterval;
                    
                    
                    
                    long temp = 0;
                    
                    if (timeInterval < 60) {
                        result = [NSString stringWithFormat:@"刚刚"];
                    }
                    else if((temp = timeInterval/60) <60){
                        result = [NSString stringWithFormat:@"%ld分前",temp];
                    }
                    
                    else if((temp = temp/60) <24){
                        result = [NSString stringWithFormat:@"%ld小时前",temp];
                    }
                    
                    else if((temp = temp/24) <30){
                        result = [NSString stringWithFormat:@"%ld天前",temp];
                    }
                    
                    else if((temp = temp/30) <12){
                        result = [NSString stringWithFormat:@"%ld月前",temp];
                    }
                    else{
                        temp = temp/12;
                        result = [NSString stringWithFormat:@"%ld年前",temp];
                    }
                    
                    
                    [pubTime addObject:result];
                }
                [noDataView removeFromSuperview];
                if (arrr.count>0) {
                    [self _AutoScrollView];
                    
                }else{
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]) {
                                       }else{
                                           noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                                           [self.view addSubview:noDataView];
                                           UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                                           noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                                           [noDataView addSubview:noImage];
                                           UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                                           noLabel.text=@"没有列表数据，赶紧去添加！";
                                           noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                                           noLabel.textAlignment=NSTextAlignmentCenter;
                                           [noDataView addSubview:noLabel];
                                           

                    }
                }
                if (arrr.count>1) {
                    [author removeObjectAtIndex:0];
                    [ImageUrl removeObjectAtIndex:0];
                    [content removeObjectAtIndex:0];
                    [fid removeObjectAtIndex:0];
                    [title removeObjectAtIndex:0];
                    [pubTime removeObjectAtIndex:0];
                }
                
                [table reloadData];
              
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
            }
            
        }
        else
        {
           [Global hideProgressHUDInternal:self.view];
//            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}
//下拉刷新
- (void)addheader
{
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        [pubTime removeAllObjects];
        [author removeAllObjects];
        [ImageUrl removeAllObjects];
        [content removeAllObjects];
        [title removeAllObjects];
        [fid removeAllObjects];
        [LinkType removeAllObjects];
        [LinkCode removeAllObjects];
        [self requestData];
        [self performSelector:@selector(userStatus) withObject:nil afterDelay:3.0f];
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:1.0f];
        
    };
}
//上拉刷新
- (void)addFooter
{
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        if (TotalCount.intValue/30>=pageNumber) {
            pageNumber++;
            NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
            NSString* tokenId = [user1 objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:tokenId forKey:@"tokenId"];
            [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            [params setValue:@"30" forKey:@"pageSize"];
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:@"/Discover/Household/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    //                    NSLog(@"====%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        NSMutableArray* arrr=[[NSMutableArray alloc]init];
                        arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                        for (NSDictionary* dicc in arrr )
                        {
                            
                            [author addObject:[dicc valueForKey:@"author"]];
                            [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                            [content addObject:[dicc valueForKey:@"content"]];
                            [fid addObject:[dicc valueForKey:@"fid"]];
                            [title addObject:[dicc valueForKey:@"title"]];
                            
                            NSString* string =  [dicc valueForKey:@"pubTime"];
                            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                            [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                            NSDate *destDate= [dateFormatter dateFromString:string];
                            NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                            timeInterval = -timeInterval;
                            long temp = 0;
                            
                            if (timeInterval < 60) {
                                result = [NSString stringWithFormat:@"刚刚"];
                            }
                            else if((temp = timeInterval/60) <60){
                                result = [NSString stringWithFormat:@"%ld分前",temp];
                            }
                            
                            else if((temp = temp/60) <24){
                                result = [NSString stringWithFormat:@"%ld小时前",temp];
                            }
                            
                            else if((temp = temp/24) <30){
                                result = [NSString stringWithFormat:@"%ld天前",temp];
                            }
                            
                            else if((temp = temp/30) <12){
                                result = [NSString stringWithFormat:@"%ld月前",temp];
                            }
                            else{
                                temp = temp/12;
                                result = [NSString stringWithFormat:@"%ld年前",temp];
                            }
                            [pubTime addObject:result];
                        }[table reloadData];
                    }else{
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }}
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
                
            }];
        }else{
            NSString *requestResultStr=@"没有更多数据了！";
            [Global showTextHudSub:requestResultStr view:self.view];
        }
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [title count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"Cell";
    HouseholdListCell* cell = (HouseholdListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"HouseholdListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    [cell.imageUrl.layer setCornerRadius:4.0];
    [cell.imageUrl.layer setBorderWidth:0.3];
    [cell.imageUrl.layer setMasksToBounds:YES];
    CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref2 = CGColorCreate(colorSpace2,(CGFloat[]){ 0.93, 0.93, 0.93, 0.93 });
    [cell.imageUrl.layer setBorderColor:colorref2];//边框颜色
    
    [cell.imageUrl setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:indexPath.row]]placeholderImage:[UIImage imageNamed:@"zhengfangxing"]];
    
    cell.title.text =[NSString stringWithFormat:@"%@",  [title objectAtIndex:indexPath.row]];
    cell.time.text =[NSString stringWithFormat:@"%@",  [pubTime objectAtIndex:indexPath.row]];
    cell.author.text =[NSString stringWithFormat:@"%@",  [author objectAtIndex:indexPath.row]];
    
    
    
    
    
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(10, 90-0.40, ScreenWidth-20, 0.40)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
  
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  90;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HouseholdDetailViewController *detailViewController = [[HouseholdDetailViewController alloc] init];
    detailViewController.ImageUrl=ImageUrl[indexPath.row];
    detailViewController.fid=fid[indexPath.row];
    detailViewController.titleStr=title[indexPath.row];
    detailViewController.content=content[indexPath.row];
    [self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
//轮播视图
- (void )_AutoScrollView {
    self.ImageUrlStr=[ImageUrl objectAtIndex:0];
    self.contentStr=[content objectAtIndex:0];
    self.titleStr=[title objectAtIndex:0];
    UIButton* button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 210)];
    [button setTitle:[fid objectAtIndex:0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    button.contentMode = UIViewContentModeScaleAspectFill;
    button.backgroundColor= [UIColor colorWithRed:250.00/255.0 green:250.00/255.0 blue:250.00/255.0 alpha:1];
    [button setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"dazhanweitu"]];
    [button  addTarget:self action:@selector(Btn:) forControlEvents:UIControlEventTouchUpInside];
    UILabel*titlelabel=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    titlelabel.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    titlelabel.backgroundColor=[UIColor blackColor];
    titlelabel.alpha=0.5;
    titlelabel.font=[UIFont systemFontOfSize:16];
    [button addSubview:titlelabel];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    label.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    label.textColor=[UIColor whiteColor];
    label.font=[UIFont systemFontOfSize:16];
    [button addSubview:label];
    table. tableHeaderView=button;
}

-(void)Btn:(UIButton*)sender{
    HouseholdDetailViewController *detailViewController = [[HouseholdDetailViewController alloc] init];
    detailViewController.fid=sender.titleLabel.text;
    detailViewController.ImageUrl=self.ImageUrlStr;
    detailViewController.titleStr=self.titleStr;
    detailViewController.content=self.contentStr;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
@end
